package com.example.minefieldkeepercloud.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.minefieldkeepercloud.R;
import com.example.minefieldkeepercloud.bean.LineChartBean;
import com.example.minefieldkeepercloud.bean.LineChartTestBean;
import com.example.minefieldkeepercloud.interfac.ApiHttpCallback;
import com.example.minefieldkeepercloud.interfac.Observer;
import com.example.minefieldkeepercloud.interfac.OnSelectParameterListener;
import com.example.minefieldkeepercloud.network.MyGson;
import com.example.minefieldkeepercloud.network.NetHelperNew;
import com.example.minefieldkeepercloud.util.DynamicLineChartManager;
import com.example.minefieldkeepercloud.util.TimeUtil;
import com.example.minefieldkeepercloud.util.ToastUtil;
import com.example.minefieldkeepercloud.view.lazyviewpager.LazyFragmentPagerAdapter;
import com.github.mikephil.charting.charts.LineChart;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 矿机算力统计图
 * @Author:Created by  ygy
 * @time:2019/12/2
 */
public class MinerChartFragment extends Fragment implements  LazyFragmentPagerAdapter.Laziable {
    @BindView(R.id.linechart)
    LineChart linechart;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    private DynamicLineChartManager dynamicLineChartManager2;

    private OnSelectParameterListener onSelectParameterListener;//参数的选择

    private int factoryId;//矿场id
    private int datetype;//日期类型
    private  String dateString="";//日期
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_miner_chart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        initChart();
        getDatas();
    }

    private void initChart() {
        List<LineChartTestBean> list = new ArrayList<>();
        String unit = "";
        float max = 6;
        for (int i = 0; i < 49; i++) {
            if (i == 0) {
                unit = "T";
            }
            list.add(new LineChartTestBean("", 0f));

        }
        List<String> names = new ArrayList<>(); //折线名字集合
        List<Integer> colour = new ArrayList<>();//折线颜色集合
        //折线名字 //折线颜色
        names.add("矿工");
        colour.add(getResources().getColor(R.color.system_color));
        tv_unit.setText("" + unit);
        dynamicLineChartManager2 = new DynamicLineChartManager(linechart, names, colour, 24, unit);
        dynamicLineChartManager2.setDescription("");
        dynamicLineChartManager2.setYAxis(max, 0, 6);
        for (int i = 0; i < list.size(); i++) {
            dynamicLineChartManager2.addEntry(list.get(i));
        }
    }


    private void init() {
        EventBus.getDefault().register(this);
        factoryId=onSelectParameterListener.getFactoryId();
        datetype=onSelectParameterListener.getDateType();
        dateString=onSelectParameterListener.getDate();



    }

    /**
     * 获取网络数据
     */
    private void getDatas() {
        if (factoryId!=0)
        NetHelperNew.GetCalPoweStatistics_Chart_Day(datetype,""+factoryId,dateString,new ApiHttpCallback(getActivity(),1,true){
            @Override
            public void onSuccess(String data) {
                super.onSuccess(data);
                Log.i("-->", datetype+"图表数据：" + data);

                LineChartBean lineChartBean = MyGson.getInstance().fromJson(data, LineChartBean.class);


                if (lineChartBean.getType() == 1) {
                    List<LineChartBean.DataBeanX.DataBean> dataBeans = lineChartBean.getData().getData();

                    boolean isAllNUll=true;//是否全是-

                    for (int i = 0; i < dataBeans.size(); i++) {
                        if (!"-".equals(dataBeans.get(i).getY())){
                            isAllNUll=false;
                        }
                    }
                    if (isAllNUll)
                    {
                        //=================================

                        List<LineChartTestBean> list=new ArrayList<>();
                        String unit=lineChartBean.getData().getDw();
                        float max = 0;
                        for (int i = 0; i <dataBeans.size(); i++) {

                            LineChartBean.DataBeanX.DataBean dataBean = dataBeans.get(i);


                            float y=0.0f;
                            if (!"-".equals(dataBean.getY()))
                            {
                                y=Float.valueOf(dataBean.getY());
                            }
                            if (i==0&&datetype==0)
                            {
                                list.add(new LineChartTestBean(dataBean.getX(), y));
                            }
                            list.add(new LineChartTestBean(dataBean.getX(), y));


                            if ((i+1)==dataBeans.size()&&datetype==1)
                            {
                                //按月统计数量不够添加空数据

                                for (int j = 0; j < 33 - dataBeans.size(); j++) {
                                    list.add(new LineChartTestBean(dataBean.getX(),  y));
                                }
                            }

                        }


                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getFilingNumber() > max) {
                                max = list.get(i).getFilingNumber();
                            }
                        }



                        List<String> names = new ArrayList<>(); //折线名字集合
                        List<Integer> colour = new ArrayList<>();//折线颜色集合
                        //折线名字 //折线颜色
                        names.add("算力统计1");


                        colour.add(getResources().getColor(R.color.system_color));




                        tv_unit.setText(""+unit);
                        dynamicLineChartManager2 = new DynamicLineChartManager(linechart, names, colour,list.size()-1,unit);
                        dynamicLineChartManager2.setDescription("");
                        dynamicLineChartManager2.setYAxis(max, 0, 6);
                        for (int i = 0; i < list.size(); i++) {
                            dynamicLineChartManager2.addEntry(list.get(i));
                        }
                        //=================================

                    }else {
                        //不全是“-”
                        List<LineChartTestBean> list=new ArrayList<>();
                        String unit=lineChartBean.getData().getDw();
                        float max = 0;
                        for (int i = 0; i <dataBeans.size(); i++) {

                            LineChartBean.DataBeanX.DataBean dataBean = dataBeans.get(i);

                            /**
                             * 测试
                             */
//                            if (i==5){
//                                dataBean.setY("-");
//                            }

                            float y=0.0f;
                            if (!"-".equals(dataBean.getY()))
                            {
                                y=Float.valueOf(dataBean.getY());
                            }else {
                                y=1.121f;
                            }
                            if (i==0&&datetype==0)
                            {
                                list.add(new LineChartTestBean("", 1.121f));
                            }
                            list.add(new LineChartTestBean(dataBean.getX(), y));


                            if ((i+1)==dataBeans.size()&&datetype==1)
                            {
                                //按月统计数量不够添加空数据

                                for (int j = 0; j < 33 - dataBeans.size(); j++) {
                                    list.add(new LineChartTestBean("",  1.121f));
                                }
                            }

                        }


                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getFilingNumber() > max) {
                                max = list.get(i).getFilingNumber();
                            }
                        }



                        List<String> names = new ArrayList<>(); //折线名字集合
                        List<Integer> colour = new ArrayList<>();//折线颜色集合


                        List<List<LineChartTestBean>> listlist=new ArrayList<>();
                        //折线名字 //折线颜色
                        names.add("算力统计1");
                        colour.add(getResources().getColor(R.color.possible_result_points));
                        listlist.add(list);
                        int num=0;
                        boolean isCreate=false;
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getFilingNumber()==1.121f)
                            {
                                isCreate=false;
                            }else {
                                if (!isCreate)
                                {
                                    List<LineChartTestBean> listsss=new ArrayList<>();
                                    names.add("算力统计");
                                    colour.add(getResources().getColor(R.color.system_color));
                                    listsss.add(list.get(i));
                                    listlist.add(listsss);
                                    num++;
                                    isCreate=true;
                                }else {
                                    listlist.get(num).add(list.get(i));
                                }
                            }


                        }
                        names.add("算力统计");
                        colour.add(getResources().getColor(R.color.possible_result_points));
                        listlist.add(list);


                        tv_unit.setText(""+unit);
                        dynamicLineChartManager2 = new DynamicLineChartManager(linechart, names, colour,list.size()-1,unit);
                        dynamicLineChartManager2.setDescription("");
                        dynamicLineChartManager2.setYAxis(max, 0, 6);
                        Log.i("-->",names.size()+"数据："+listlist.toString());
//                        for (int i = 0; i < list.size(); i++) {
//                            dynamicLineChartManager2.addEntry(list.get(i));
//                        }


                        dynamicLineChartManager2.addAllEntry(listlist);
                    }

                } else {

                    ToastUtil.showToast(getActivity(),lineChartBean.getContent());

                   initChart();
                }
            }
        });
    }


    // 当FRagmen被加载到activity的时候会被回调
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof OnSelectParameterListener) {
            onSelectParameterListener = (OnSelectParameterListener) activity; // 2.2 获取到宿主activity并赋值
        } else {
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }

    //把传递进来的activity对象释放掉
    @Override
    public void onDetach() {
        super.onDetach();
        onSelectParameterListener = null;
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void handleData(String str) {

        if (onSelectParameterListener!=null&&str.equals("10")) {
            this.datetype=onSelectParameterListener.getDateType();
            this.dateString=onSelectParameterListener.getDate();
            this.factoryId=onSelectParameterListener.getFactoryId();

            getDatas();

        }


    }
}
